package com.nearby.android.unitl;

import java.util.ArrayList;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.FloatMath;
import android.util.Log;

/**
 * 1、new一个ShakeDetector
 * 2、调用mShakeDetector.registerOnShakeListener()注册一个OnShakeListener
 * 3、在OnShakeListener的onShake函数中，处理摇晃事件
 * 4、调用mShakeDetector.start()启动摇晃检测
*/

public class ShakeDetector implements SensorEventListener{
	//检测的时间间隔
	static final int UPDATE_INTERVAL = 100;
	//上一次检测的时间
	long mLastUpdateTime;
	//上一次检测时，加速度在x,y,x方向上的分量，用于和当前加速度比较求差
	float mLastX, mLastY, mLastZ;
	Context mContext;
	SensorManager mSensorManager;
	ArrayList<OnShakeListener> mListeners;
	
	public int shakeThreshold = 3000;
	
	public ShakeDetector(Context context){
		mContext = context;
		mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
		mListeners = new ArrayList<OnShakeListener>();
	}
	public interface OnShakeListener{
		//当手机晃动时被调用
		void onShake();
	}
	//注册OnShakeListener 当摇晃时接受通知
	public void registerOnShakeListener(OnShakeListener listener){
		if(mListeners.contains(listener))
			return;
		mListeners.add(listener);
	}
	//移除已经注册的OnShakeListener
	public void unregisterOnShakeListener(OnShakeListener listener){
		mListeners.remove(listener);
	}
	//启动摇晃检测
	public void start(){
		if(mSensorManager == null){
			throw new UnsupportedOperationException();
		}
		Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		if(sensor == null){
			throw new UnsupportedOperationException();
		}
		boolean success = mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
		if(!success){
			throw new UnsupportedOperationException();
		}
	}
	//停止摇晃检测
	public void stop(){
		if(mSensorManager != null){
			mSensorManager.unregisterListener(this);
		}
	}
	

	
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		long currentTime = System.currentTimeMillis();
		long diffTime = currentTime - mLastUpdateTime;
		if(diffTime < UPDATE_INTERVAL)
			return;
		mLastUpdateTime = currentTime;
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];
		float deltaX = x - mLastX;
		float deltaY = y - mLastY;
		float deltaZ = z - mLastZ;
		
		mLastX = x;
		mLastY = y;
		mLastZ = z;
		
		float delta = FloatMath.sqrt(deltaX*deltaX + deltaY*deltaY + deltaZ*deltaZ)/diffTime * 10000;
		
		Log.i("test", String.valueOf(delta));
		
		if(delta > shakeThreshold){//当加速度的差值大于指定的阈值，认为这是一个摇晃
			this.notifyListeners();
		}
	}
	private void notifyListeners(){
		for(OnShakeListener listener : mListeners){
			listener.onShake();
		}
	}
}
